package controllers

import (
	"encoding/json"

	. "fanhantech.com/tagdata/message"
	"fanhantech.com/tagdata/models"
	"fanhantech.com/tagdata/utils"
	"github.com/astaxie/beego"
)

type UserController struct {
	beego.Controller
}

type ResponseUser struct {
	Username string `json:"username"`
	Status   string `json:"status"`
	Role     string `json:"role"`
}

// Get /api/user/:username [GET]
func (c *UserController) QueryUser() {
	username := c.Ctx.Input.Param(":username")
	users, err := models.QueryUserByUsername(username)
	if err != nil {
		c.Data["json"] = NewResponseFor("user.query.fail")
		c.ServeJSON()
		return
	}

	responseUsers := make([]ResponseUser, 0)
	for _, user := range users {
		responseUser := ResponseUser{}
		responseUser.Username = user.Username
		switch user.Status {
		case 1:
			responseUser.Status = "正常"
		default:
			responseUser.Status = "禁止"
		}
		switch user.Role {
		case 1:
			responseUser.Role = "管理员"
		case 2:
			responseUser.Role = "项目经理"
		default:
			responseUser.Role = "普通用户"
		}
		responseUsers = append(responseUsers, responseUser)
	}
	rsp := NewResponse()
	rsp.Data = responseUsers
	c.Data["json"] = rsp
	c.ServeJSON()
}

type FormUser struct {
	Username string `valid:"Required;AlphaDash"`
	Password string `valid:"Required"`
}

// Post /api/user [POST]
func (c *UserController) CreateUser() {
	user := FormUser{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
	if err != nil {
		c.Data["json"] = NewResponseFor("user.data.verification.error")
		c.ServeJSON()
		return
	}
	err = models.CreateUser(user.Username, utils.Md5(user.Password))
	if err != nil {
		rsp := NewResponseFor("user.create.fail")
		beego.Info(rsp.Message)
		c.Data["json"] = rsp
		c.ServeJSON()
		return
	}
	c.Data["json"] = NewResponseFor("user.create.success")
	c.ServeJSON()
}

// Post /api/user/:username/password [POST]
func (c *UserController) UpdatePassword() {
	user := FormUser{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
	if err != nil {
		c.Data["json"] = NewResponseFor("user.data.verification.error")
		c.ServeJSON()
		return
	}
	err = models.UpdateUserPassword(user.Username, utils.Md5(user.Password))
	if err != nil {
		c.Data["json"] = NewResponseFor("user.password.update.fail")
		c.ServeJSON()
		return
	}
	c.Data["json"] = NewResponseFor("user.password.update.success")
	c.ServeJSON()
}
